#include "main.h"

/*打印用户界面*/
void printf_user(void)
{
	printf("-----------------\n");
	printf("输入\t命令\n");
	printf("-----------------\n");
	printf("1\t登录\n");
	printf("2\t注册\n");
	printf("0\t退出\n");
	printf("-----------------\n");
}

void gettime(char** ptime)
{
	char curtime[20];
  time_t tm;
	struct tm *p;
	
  time(&tm);
  p = localtime(&tm);
  snprintf(curtime, 20, "%d-%d-%d %2d:%2d:%2d", 1900+p->tm_year, 1+p->tm_mon, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);
	*ptime = curtime;
}

int login(int fd,MSG* pmsg)
{
	memset(pmsg,0,sizeof(MSG));
	pmsg->type = 'L';//命令类型：登录

	/*输入用户名和密码*/
	printf("============登录============\n");
	printf(">>用户名：");
	scanf("%s",pmsg->username);
	fflush(stdin);
	printf(">>密码：");
	scanf("%s",pmsg->info);
	fflush(stdin);

	/*将用户信息发送给服务器*/
	write(fd,pmsg,sizeof(MSG));

	/*等待服务器返回验证结果*/
	usleep(500000);
	read(fd,pmsg,sizeof(MSG));
	printf("server>>%s\n",pmsg->info);

	if(strncmp(pmsg->info,"FAIL",4) == 0)
	{
		printf("登录失败。\n");
		printf("用户名或密码错误。\n");
		return 1;
	}
	else if(strncmp(pmsg->info,"SUCCESS",7) == 0)
	{
		printf("登录成功！\n");
		close(fd);
		return 0;
	}
	else
	{
		printf("服务器响应出错。\n");
		return 1;
	}	
}

int regis(int fd,MSG* pmsg)
{
	char password2[50];

	memset(pmsg,0,sizeof(MSG));
	pmsg->type = 'R';//命令类型：注册

	/*输入用户名和密码*/
	printf("============注册============\n");
	printf(">>用户名：");
	scanf("%s",pmsg->username);
	fflush(stdin);
	REPWD:
	printf(">>密码：");
	scanf("%s",pmsg->info);
	fflush(stdin);
	printf(">>请再次输入密码：");
	scanf("%s",password2);
	fflush(stdin);

	if(strncmp(pmsg->info,password2,50) != 0)
	{
		printf("两次输入的密码不一致，请重新输入。\n");
		goto REPWD;
	}

	/*将用户信息发送给服务器*/
	write(fd,pmsg,sizeof(MSG));

	/*等待服务器返回验证结果*/
	usleep(500000);
	read(fd,pmsg,sizeof(MSG));
	printf("server>>%s\n",pmsg->info);

	if(strncmp(pmsg->info,"FAIL",4) == 0)
	{
		printf("注册失败。\n");
		printf("该用户已存在。\n");
		return 1;
	}
	else if(strncmp(pmsg->info,"SUCCESS",7) == 0)
	{
		printf("注册成功！\n");
		return 0;
	}
	else
	{
		printf("服务器响应出错。\n");
		return 1;
	}	
}


